<?php

namespace app\api\controller\xiluhouse;

use app\common\controller\Api;
use app\common\model\xiluhouse\House as HouseModel;
use app\common\model\xiluhouse\HouseLayout as HouseLayoutModel;
use app\common\model\xiluhouse\HouseCollect as HouseCollectModel;
use app\common\model\xiluhouse\HouseSearchRoomnum;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * @title   房源类
 * @desc    获取房源、房源相关信息的接口
 */
class House extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['region_house_data', 'region_latlng_house_data', 'house_list', 'house_detail', 'trends_list', 'house_building_info', 'house_layout_info', 'house_layout_list', 'house_layout_detail', 'comment_info', 'comment_list', 'free_car_num', 'my_view_list', 'share_qrcode', 'house_default_broker', 'create_special_log'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new HouseModel();
    }

    /**
     * @title   地图找房的区县
     * @desc    地图找房的区县
     * @param string $city   上海市   城市
     * @param string    $keyword          无                    搜索关键词
     */
    public function region_house_data()
    {
        $city = $this->request->param('city/s', '上海市');
        $map['status'] = 'normal';
        $keyword = $this->request->param('keyword/s', '');
        if ($keyword) {
            $map['name|region'] = ['like', '%' . $keyword . '%'];
        }
        $data = $this->model
            ->field('region,count(*) as count,lat,lng')
            ->where('city', 'like', $city . '%')
            ->where($map)
            ->group('region')
            ->select();
        foreach ($data as $key => $value) {
            $value->visible(['region', 'count', 'lat', 'lng']);
        }
        $this->success('', $data);
    }

    /**
     * @title   地图找房的楼盘
     * @desc    地图找房的区县
     * @param string $city   上海市   城市
     * @param string $min_lat   无   最小纬度
     * @param string $max_lat   无   最大纬度
     * @param string $min_lng   无   最小经度
     * @param string $max_lng   无   最大经度
     * @param string    $keyword          无                    搜索关键词
     */
    public function region_latlng_house_data()
    {
        $city = $this->request->param('city/s', '上海市');
        $min_lat = $this->request->param('min_lat/f', '');
        $max_lat = $this->request->param('max_lat/f', '');
        $min_lng = $this->request->param('min_lng/f', '');
        $max_lng = $this->request->param('max_lng/f', '');
        $keyword = $this->request->param('keyword/s', '');
        if ($keyword) {
            $map['name|region'] = ['like', '%' . $keyword . '%'];
        }
        $map['status'] = 'normal';
        $map['city'] = ['like', $city . '%'];
        if ($max_lat && $min_lat && $max_lat > $min_lat) {
            $map['lat'] = ['between', [$min_lat, $max_lat]];
        }
        if ($max_lng && $min_lng && $max_lng > $min_lng) {
            $map['lng'] = ['between', [$min_lng, $max_lng]];
        }
        $data = $this->model
            ->where($map)
            ->order('weigh desc,id desc')
            ->select();
        foreach ($data as $datas) {
            $datas->append(['house_tag_ids_text_arr']);
        }

        $this->success('', $data);
    }

    /**
     * @title  房源列表
     * @desc  获取-房源列表
     * @param string    $city             上海市                城市
     * @param string    $region           无                    区域
     * @param string    $street           无                    街道/镇
     * @param string    $keyword          无                    搜索关键词
     * @param string    $lat              31.235929042252       纬度
     * @param string    $lng              121.48053886018       经度
     * @param tinyint   $nearby           无                    附近几公里
     * @param int       $subway_id         无                   地铁线id
     * @param int       $subway_platform_id 无                  地铁站id
     * @param decimal   $min_average_price  0                   最小单价（万元）
     * @param decimal   $max_average_price  0                   最大单价（万元）（-1为无限大）
     * @param decimal   $min_total_price    0                   最小总价（万元）
     * @param decimal   $max_total_price    0                   最大总价（万元）（-1为无限大）
     * @param string    $search_roomnum_ids 无                   查询户型(多个id用英文逗号隔开)
     * @param string    $type_ids           无                   查询类型(多个id用英文逗号隔开)
     * @param string    $developer_ids       无                   查询开发商(多个id用英文逗号隔开)
     * @param string    $tag_ids            无                   查询标签(多个id用英文逗号隔开)
     * @param tinyint   $sale_state        无                    售卖情况:1=在售,2=售罄,3=待售
     * @param int       $sort              1                    排序:1=默认排序，2=看房次数从大到小（人气排行榜），3=单价从小到大，4=单价从大到小，5=成交量从大到小(热销排行榜)
     *
     */
    public function house_list()
    {
        $map['status'] = 'normal';


        $keyword = $this->request->param('keyword/s', '');
        $map_text = '';
        if ($keyword) {
            $map['name'] = ['like', '%' . $keyword . '%'];
        } else {
            $map['city'] = ['like', $this->request->param('city/s', '上海市') . '%'];
            $region = $this->request->param('region/s', '');
            if ($region) {
                $map['region'] = ['like', $region . '%'];
            }
            $street = $this->request->param('street/s', '');
            if ($street) {
                $map['street'] = ['like', $street . '%'];
            }
            $subway_id = $this->request->param('subway_id/d', 0);
            if ($subway_id) {
                $map_text = $map_text ? $map_text . ' and ' : $map_text;
                $map_text .= 'FIND_IN_SET(' . $subway_id . ',subway_ids)';
            }
            $subway_platform_id = $this->request->param('subway_platform_id/d', 0);
            if ($subway_platform_id) {
                $map['subway_platform_id'] = $subway_platform_id;
            }
        }

        $nearby = $this->request->param('nearby/d', 0);
        if ($nearby) {
            $lat = floatval($this->request->param('lat/s', '31.235929042252'));
            $lng = floatval($this->request->param('lng/s', '121.48053886018'));
            $map_text = '(ACOS(SIN((' . $lat . '*3.1415)/180)*SIN((lat*3.1415)/180)+COS((' . $lat . '*3.1415)/180)*COS((lat*3.1415)/180)*COS((' . $lng . '*3.1415)/180-(lng*3.1415)/180))*6380) <=' . $nearby;
        }



        $min_average_price = $this->request->param('min_average_price/f', 0);
        $max_average_price = $this->request->param('max_average_price/f', 0);
        if ($max_average_price > 0) {
            $map['price'] = ['BETWEEN', (10000 * $min_average_price) . ',' . (10000 * $max_average_price)];
        } else if ($max_average_price == -1) {
            $map['price'] = ['egt', 10000 * $min_average_price];
        }

        $min_total_price = $this->request->param('min_total_price/f', 0);
        $max_total_price = $this->request->param('max_total_price/f', 0);
        if ($max_total_price > 0) {
            $map_text = $map_text ? $map_text . ' and ' : $map_text;
            $map_text .= '((min_total_price >= ' . $min_total_price . ' and min_total_price <= ' . $max_total_price . ') or (max_total_price >= ' . $min_total_price . ' and max_total_price <= ' . $max_total_price . '))';
        } else if ($max_total_price == -1) {
            $map['max_total_price'] = ['egt', $min_total_price];
        }

        $search_roomnum_ids = $this->request->param('search_roomnum_ids/s', '');
        if ($search_roomnum_ids) {
            $search_roomnum_data = \app\common\model\xiluhouse\HouseSearchRoomnum::where('status', 'normal')->where('id', 'in', $search_roomnum_ids)->select();
            $roomnum_map_arr = [];
            foreach ($search_roomnum_data as $value) {
                if ($value['max_room_num'] == -1) {
                    $roomnum_map_arr[] = '(max_room_num >= ' . $value['min_room_num'] . ')';
                } else {
                    $roomnum_map_arr[] = '((min_room_num >= ' . $value['min_room_num'] . ' and min_room_num <= ' . $value['max_room_num'] . ') or (max_room_num >= ' . $value['min_room_num'] . ' and max_room_num <= ' . $value['max_room_num'] . '))';
                }
            }
            if (!empty($roomnum_map_arr)) {
                $map_text = $map_text ? $map_text . ' and ' : $map_text;
                $map_text .= implode(' or ', $roomnum_map_arr);
            }
        }

        $type_ids = $this->request->param('type_ids/s', '');
        if ($type_ids) {
            $map['house_type_id'] = ['in', $type_ids];
        }

        $developer_ids = $this->request->param('developer_ids/s', '');
        if ($developer_ids) {
            $map['house_developer_id'] = ['in', $developer_ids];
        }

        //查询房屋特色 例如 1,2,3  多个 字符串
        $tag_ids = $this->request->param('tag_ids/s', '');
        if ($tag_ids) {
            $arr = explode(',', $tag_ids);
            $tag_ids_map_arr = [];
            foreach ($arr as $key => $value) {
                $tag_ids_map_arr[] = 'FIND_IN_SET(' . intval($value) . ',house_tag_ids)';
            }
            if (!empty($tag_ids_map_arr)) {
                $map_text = $map_text ? $map_text . ' and ' : $map_text;
                $map_text .= implode(' or ', $tag_ids_map_arr);
            }
        }

        $sale_state = $this->request->param('sale_state/d', 0);
        if ($sale_state) {
            $map['sale_state'] = $sale_state;
        }

        // 排序:1=默认排序，2=看房次数从大到小，3=单价从小到大，4=单价从大到小，5=成交量从大到小
        $sort = $this->request->param('sort/d', 1);
        switch ($sort) {
            case 2:
                # 看房次数从大到小
                $order = ['view_num' => 'desc', 'weigh' => 'desc', 'id' => 'desc'];
                break;
            case 3:
                # 单价从小到大
                $order = ['price' => 'asc', 'weigh' => 'desc', 'id' => 'desc'];
                break;
            case 4:
                # 单价从大到小
                $order = ['price' => 'desc', 'weigh' => 'desc', 'id' => 'desc'];
                break;
            case 5:
                # 成交量从大到小
                $order = ['sale_num' => 'desc', 'weigh' => 'desc', 'id' => 'desc'];
                break;

            default:
                # 默认排序
                $order = ['weigh' => 'desc', 'id' => 'desc'];
                break;
        }

        $list = $this->model->where($map)->where($map_text)->order($order)->paginate();
        foreach ($list as &$datas) {
            $datas->append(['house_tag_ids_text_arr', 'house_tag_ids_text_arr2', 'house_tag_ids_text1', 'house_type_id_text', 'is_collect']);
            if ($keyword) {
                $datas->append(['name_arr']);
                $tmp_arr = explode('???', str_replace($keyword, "???" . $keyword . "???", $datas['name']));
                $tmp_arr2 = [];
                foreach ($tmp_arr as $key => $value) {
                    if ($value) {
                        $tmp_arr2[] = [
                            'is_active' => $value == $keyword ? true : false,
                            'value' => $value,
                        ];
                    }
                }
                $datas['name_arr'] = $tmp_arr2;
            }
        }
        $this->success('', $list);
    }

    /**
     * @title   房源详情
     * @desc    房源详情
     * @param int $id   0   房源id
     */
    public function house_detail()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }
        $info = $this->model->with(['housetype'])->find($id);
        if (!$info) {
            $this->error('查询不到该房源');
        }
        if ($info['status'] != 'normal') {
            $this->error('该房源已下架');
        }
        $info->append(['images_arr2', 'images_arr', 'house_tag_ids_text_arr', 'building_descript_arr', 'property_descript_arr', 'nearby_bus_json_arr', 'nearby_subway_json_arr', 'nearby_school_json_arr', 'nearby_shop_json_arr', 'nearby_hospital_json_arr', 'rank_json_arr','mapimg']);

        // 处理获取静态地图图片
        $info['mapimg']=getGeoImg($info['lat'],$info['lng']);
        $data['house_info'] = $info;
        // 处理看房记录
        if ($this->auth && $this->auth->id) {
            \app\common\model\xiluhouse\HouseView::create(['house_id' => $id, 'user_id' => $this->auth->id]);
        }
        // 获取排行榜
        $data['rank_data'] = $info['rank_json_arr'];
        // 判断是否收藏
        $data['house_info']['is_collect'] = false;
        if ($this->auth && $this->auth->id) {
            $exist = \app\common\model\xiluhouse\HouseCollect::where('type', 1)->where('house_id', $id)->where('user_id', $this->auth->id)->find();
            if ($exist) {
                $data['house_info']['is_collect'] = true;
            }
        }
        // 所有楼盘楼栋信息
        $build_arr = \app\common\model\xiluhouse\HouseBuilding::where('status', 'normal')->where('house_id', $id)->column('name');
        $data['house_info']['all_build_name'] = !empty($build_arr) ? implode(',', $build_arr) : '';
        // 所有户型信息
        $layout_model = new \app\common\model\xiluhouse\HouseLayout;
        $layout_data = [];
        $tmp_data = $layout_model->where('house_id', $id)->field('room_num,count(*) as total_num')->where('status', 'normal')->group('room_num')->select();
        foreach ($tmp_data as $key => $value) {
            $layout_data[] = number2chinese($value['room_num']) . '居(' . $value['total_num'] . ')';
        }
        $data['house_info']['all_layout_name'] = !empty($layout_data) ? implode(',', $layout_data) : '';

        // 获取推荐经纪人
        $data['house_info']['default_broker'] = \app\common\model\xiluhouse\HouseBroker::with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'profile'])->where('house_broker.status', 'normal')->where('user.status', 'normal')->where('profile.is_broker', 2)->where('house_id', $id)->order('is_recommend desc,weigh desc')->find();
        // 经纪人列表
        $data['broker_data'] = \app\common\model\xiluhouse\HouseBroker::with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'profile'])->where('house_broker.status', 'normal')->where('user.status', 'normal')->where('profile.is_broker', 2)->where('house_id', $id)->order('is_recommend desc,weigh desc')->select();
        // 获取户型
        $data['layout_info']['layout_data'] = \app\common\model\xiluhouse\HouseLayout::where('status', 'normal')->where('house_id', $id)->orderRaw('weigh desc,id desc')->limit(2)->select();
        $data['layout_info']['layout_count'] = \app\common\model\xiluhouse\HouseLayout::where('status', 'normal')->where('house_id', $id)->count();
        // 获取楼栋信息
        $data['building_info']['building_count'] = \app\common\model\xiluhouse\HouseBuilding::where('status', 'normal')->where('house_id', $id)->count();
        $data['building_info']['building_image'] = $info['build_image_text'];
        // 获取动态信息
        $data['trends_info']['trends_count'] = \app\common\model\xiluhouse\HouseTrends::where('status', 'normal')->where('house_id', $id)->count();
        $data['trends_info']['trends_data'] = [];
        $temp_dta = \app\common\model\xiluhouse\HouseTrends::where('status', 'normal')->where('house_id', $id)->where('type', 1)->orderRaw('show_date desc')->find();
        if ($temp_dta) {
            $data['trends_info']['trends_data'][] = $temp_dta;
        }
        $temp_dta = \app\common\model\xiluhouse\HouseTrends::where('status', 'normal')->where('house_id', $id)->where('type', 2)->orderRaw('show_date desc')->find();
        if ($temp_dta) {
            $data['trends_info']['trends_data'][] = $temp_dta;
        }
        $temp_dta = \app\common\model\xiluhouse\HouseTrends::where('status', 'normal')->where('house_id', $id)->where('type', 3)->orderRaw('show_date desc')->find();
        if ($temp_dta) {
            $data['trends_info']['trends_data'][] = $temp_dta;
        }
        $temp_dta = \app\common\model\xiluhouse\HouseTrends::where('status', 'normal')->where('house_id', $id)->where('type', 4)->orderRaw('show_date desc')->find();
        if ($temp_dta) {
            $data['trends_info']['trends_data'][] = $temp_dta;
        }
        // 最新销售许可证
        $data['house_info']['cert_trends_newinfo'] = isset($data['trends_info']['trends_data'][3]) ? $data['trends_info']['trends_data'][3] : null;
        // 所有销售许可证
        $data['house_info']['cert_trends_data'] = \app\common\model\xiluhouse\HouseTrends::where('status', 'normal')->where('house_id', $id)->where('type', 4)->orderRaw('show_date desc')->select();
        // 获取一条楼市头条
        $data['article_info']['article_data'] = \app\common\model\xiluhouse\Article::with(['articlecategory'])->where('article.status', 'normal')->where('article.classify', 2)->orderRaw('weigh desc,id desc')->limit(1)->select();
        $data['article_info']['article_count'] = \app\common\model\xiluhouse\Article::where('status', 'normal')->where('classify', 2)->count();
        // 获取用户点评
        $data['user_comment_info']['comment_count'] = \app\common\model\xiluhouse\Comment::where('type', 1)->where('house_id', $id)->where('comment_type', 1)->count();
        $comment_data = \app\common\model\xiluhouse\Comment::with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }])->where('type', 1)->where('house_id', $id)->where('comment_type', 1)->order('id desc')->limit(3)->select();
        foreach ($comment_data as &$value) {
            $value->append(['is_like']);
        }
        $data['user_comment_info']['comment_data'] = $comment_data;
        // 获取咨询师点评
        $data['broker_comment_info']['comment_count'] = \app\common\model\xiluhouse\Comment::where('type', 1)->where('house_id', $id)->where('comment_type', 2)->count();
        $comment_data = \app\common\model\xiluhouse\Comment::with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }])->where('type', 1)->where('house_id', $id)->where('comment_type', 2)->order('id desc')->limit(1)->select();
        foreach ($comment_data as &$value) {
            $value->append(['is_like']);
        }
        $data['broker_comment_info']['comment_data'] = $comment_data;
        // 获取推荐房源
        $data['recommend_data'] = HouseModel::where('id', 'neq', $id)->where('status', 'normal')->where('prov', $info['prov'])->where('city', $info['city'])->orderRaw('rand()')->limit(5)->select();
        foreach ($data['recommend_data'] as $recommend_value) {
            $recommend_value->append(['house_tag_ids_text_arr']);
        }
        // 给房源添加浏览量
        $info->setInc('view_num');
        $data['house_info']['platform_contact_tel'] = \app\common\model\xiluhouse\Config::getdatas('platform_contact_tel');

        // 获取关联该房源的卖房问问
        $data['question_data'] = \app\common\model\xiluhouse\QAndA::where('find_in_set(' . $id . ',house_ids)')->where('status', 'normal')->where('state', 2)->orderRaw('weigh desc,id desc')->limit(2)->select();
        $this->success('', $data);
    }

    /**
     * @title   房源默认咨询师
     * @desc    房源默认咨询师
     * @param int $id   0   房源id
     */
    public function house_default_broker()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }
        $info = $this->model->find($id);
        if (!$info) {
            $this->error('查询不到该房源');
        }
        if ($info['status'] != 'normal') {
            $this->error('该房源已下架');
        }
        // 获取推荐经纪人
        $default_broker = \app\common\model\xiluhouse\HouseBroker::with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'profile'])->where('house_broker.status', 'normal')->where('user.status', 'normal')->where('profile.is_broker', 2)->where('house_id', $id)->order('is_recommend desc,weigh desc')->find();
        $this->success('', $default_broker);
    }

    /**
     * @title  分享时需要获取小程序码
     * @desc  分享时需要获取小程序码
     *
     * @param int    $id             0            文章id
     *
     */
    public function share_qrcode()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }
        $model = new \app\common\model\xiluhouse\HouseQrcode;
        $exist = $model->where('house_id', $id)->where('user_id', $this->auth->id)->find();
        if ($exist) {
            $this->success('', cdnurl($exist['url'],true));
        }
        $wxmini = new \app\common\library\xiluhouse\Wxmini;
        $res = $wxmini->getWXacode('user_' . $this->auth->id . ',house_' . $id, 'pages/house/building_detail/building_detail');

        if(!$res) $this->error('获取小程序二维码失败');
        $root = '.';
        $filename = md5(mt_rand()).'.png';
        $path = "/uploads/".date('Ymd').'/';
        if (!file_exists($root . $path)) {
            @mkdir($root . $path, 0777, true);
        }
        $qrcode = $path.$filename;
        if(!get_addon_config('alioss')){
            file_put_contents($root.$qrcode,$res);
        }else{
            Common::uploadAlioss($path, $res);
        }
        if ($qrcode) {
            $model->save(['house_id' => $id, 'user_id' => $this->auth->id, 'url' => $qrcode]);
        }
        if(!$qrcode){
            $qrcode = \app\common\model\xiluhouse\Config::getdatas('wxmini_logo');
        }
        $share_qrcode_text = cdnurl($qrcode,true);
        $this->success('', $share_qrcode_text);
    }

    

    /**
     * @title  我的收藏（房源、户型）
     *
     */
    public function my_collect_list()
    {
        $model = new \app\common\model\xiluhouse\HouseCollect;
        $map['user_id'] = $this->auth->id;

        $list = $model->with(['house', 'houselayout'])->where($map)->order('id desc')->paginate();
        foreach ($list as $datas) {
            if ($datas['type'] == 1) {
                $datas->appendRelationAttr('house', ['house_tag_ids_text_arr']);
            }
        }
        $this->success('', $list);
    }

    /**
     * @title  我的浏览
     *
     */
    public function my_view_list()
    {
        $model = new \app\common\model\xiluhouse\HouseView;
        $map['user_id'] = $this->auth->id;
        $map['house.status'] = 'normal';
        $list = $model->with(['house'])->where($map)->order('id desc')->paginate();
        $this->success('', $list);
    }

    /**
     * @title  关注收藏房源、户型或取消关注收藏房源、户型
     * @desc  关注收藏房源或取消关注收藏房源、户型
     *
     * @param int    $house_id            0      房源id
     * @param int    $house_layout_id     0      户型id
     * @param int    $type               1      类型:1=楼盘收藏,2=户型收藏
     *
     */
    public function collect_house()
    {
        $type = $this->request->param('type/d', 1);
        $house_id = $this->request->param('house_id/d', 0);
        $house_layout_id = $this->request->param('house_layout_id/d', 0);
        if ($type == 1 && !$house_id) {
            $this->error('参数错误：房源id必传');
        }
        if ($type == 2 && !$house_layout_id) {
            $this->error('参数错误：户型id必传');
        }
        $like_model = new HouseCollectModel();
        $saveData = [];
        if ($type == 1) {
            $info = $this->model->get($house_id);
            if (!$info) {
                $this->error('不存在该房源');
            }
            if ($info['status'] != 'normal') {
                $this->error('该房源不存在');
            }

            $exist = $like_model->where('type', 1)->where('house_id', $house_id)->where('user_id', $this->auth->id)->find();
            if ($exist) {
                $res = $exist->delete();
                if (!$res) {
                    $this->error('取消收藏失败');
                }
                $this->success('取消收藏成功');
            }
        } else {
            $model = new HouseLayoutModel;
            $info = $model->get($house_layout_id);
            if (!$info) {
                $this->error('不存在该户型');
            }
            if ($info['status'] != 'normal') {
                $this->error('该户型不存在');
            }

            $exist = $like_model->where('type', 2)->where('house_layout_id', $house_layout_id)->where('user_id', $this->auth->id)->find();
            if ($exist) {
                $res = $exist->delete();
                if (!$res) {
                    $this->error('取消收藏失败');
                }
                $this->success('取消收藏成功');
            }
        }
        // 启动事务
        Db::startTrans();
        try {
            $res = $like_model->save([
                'type' => $type,
                'house_id' => $house_id,
                'house_layout_id' => $house_layout_id,
                'user_id' => $this->auth->id,
            ]);
            if (!$res) {
                exception('提交失败，请稍后提交');
            }
            $res = $info->setInc('collect_num');
            if (!$res) {
                exception('提交失败，请稍后提交');
            }
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('收藏成功');
    }

    /**
     * @title   动态信息列表
     * @desc    动态信息列表
     * @param int $house_id     0   房源id
     * @param int $type         1   类型:1=动态信息,2=开盘信息,3=交房信息,4=证件信息
     */
    public function trends_list()
    {

        $map['type'] = $this->request->param('type/d', 1);
        $map['house_id'] = $this->request->param('house_id/d', 0);
        $map['status'] = 'normal';
        if (!$map['house_id']) {
            $this->error('参数错误');
        }
        $model = new \app\common\model\xiluhouse\HouseTrends;
        $list = $model->where($map)->orderRaw('weigh desc,id desc')->paginate();
        $this->success('', $list);
    }

    /**
     * @title   楼栋信息
     * @desc    楼栋信息
     * @param int $house_id   0   房源id
     */
    public function house_building_info()
    {
        $id = $this->request->param('house_id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }
        $info = $this->model->with(['housetype'])->find($id);
        if (!$info) {
            $this->error('查询不到该房源');
        }
        if ($info['status'] != 'normal') {
            $this->error('该房源已下架');
        }
        $info['default_broker'] = \app\common\model\xiluhouse\HouseBroker::with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'profile'])->where('house_broker.status', 'normal')->where('user.status', 'normal')->where('profile.is_broker', 2)->where('house_id', $id)->order('is_recommend desc,weigh desc')->find();
        $info['platform_contact_tel'] = \app\common\model\xiluhouse\Config::getdatas('platform_contact_tel');
        $data['house_info'] = $info;

        $data['building_data'] = \app\common\model\xiluhouse\HouseBuilding::where('status', 'normal')->where('house_id', $id)->orderRaw('weigh desc,id desc')->select();
        $data['building_count'] = count($data['building_data']);
        $data['building_image'] = $info['build_image_text'];
        $this->success('', $data);
    }

    /**
     * @title   户型统计数据
     * @desc    户型统计数据
     * @param int $house_id             0   房源id
     */
    public function house_layout_info()
    {
        $map = [];
        $house_id = $this->request->param('house_id/d', 0);
        if ($house_id) {
            $map['house_id'] = $house_id;
        }

        $model = new \app\common\model\xiluhouse\HouseLayout;
        // 全部
        $all_count = $model->where($map)->where('status', 'normal')->count();
        $data = [];
        $data[] = [
            'name' => '全部',
            'count' => $all_count,
            'room_num' => 0,
        ];
        $tmp_data = $model->where($map)->field('room_num,count(*) as total_num')->where('status', 'normal')->group('room_num')->select();
        foreach ($tmp_data as $key => $value) {
            $data[] = [
                'name' => number2chinese($value['room_num']) . '居',
                'count' => $value['total_num'],
                'room_num' => $value['room_num'],
            ];
        }
        $this->success('', $data);
    }

    /**
     * @title   户型列表
     * @desc    户型列表
     * @param int $house_id             0   房源id
     * @param int $room_num             无   几室
     * @param int $house_building_id   无   关联楼栋id
     */
    public function house_layout_list()
    {
        $id = $this->request->param('house_id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }
        $info = $this->model->with(['housetype'])->find($id);
        if (!$info) {
            $this->error('查询不到该房源');
        }
        if ($info['status'] != 'normal') {
            $this->error('该房源已下架');
        }
        $map['house_id'] = $id;
        $room_num = $this->request->param('room_num/d', 0);
        if ($room_num) {
            $map['room_num'] = $room_num;
        }
        $house_building_id = $this->request->param('house_building_id/d', 0);
        if ($house_building_id) {
            $map['house_building_id'] = $house_building_id;
        }

        $model = new \app\common\model\xiluhouse\HouseLayout;
        $list = $model->where($map)->orderRaw('weigh desc,id desc')->paginate();
        $this->success('', $list);
    }

    /**
     * @title   户型详情
     * @desc    户型详情
     * @param int $id             0   户型id
     */
    public function house_layout_detail()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误');
        }
        $model = new \app\common\model\xiluhouse\HouseLayout;
        $info = $model->with(['house'])->find($id);
        if (!$info) {
            $this->error('查询不到该户型');
        }
        if (!$info['house'] || $info['house']['status'] != 'normal') {
            $this->error('该房源已下架');
        }
        if ($info['status'] != 'normal') {
            $this->error('该户型已下架');
        }
        // 判断是否收藏
        $info['is_collect'] = false;
        if ($this->auth && $this->auth->id) {
            $exist = \app\common\model\xiluhouse\HouseCollect::where('type', 2)->where('house_layout_id', $id)->where('user_id', $this->auth->id)->find();
            if ($exist) {
                $info['is_collect'] = true;
            }
        }
        // 获取默认经纪人
        $info['default_broker'] = \app\common\model\xiluhouse\HouseBroker::with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'profile'])->where('house_broker.status', 'normal')->where('user.status', 'normal')->where('profile.is_broker', 2)->where('house_id', $info['house_id'])->order('is_recommend desc,weigh desc')->find();
        $info['house']['platform_contact_tel'] = \app\common\model\xiluhouse\Config::getdatas('platform_contact_tel');
        $data['layout_info'] = $info;
        // 本楼盘其他户型
        $data['orther_layout_data'] = $model->where('house_id', $info['house_id'])->where('status', 'normal')->where('id', 'neq', $id)->orderRaw('weigh desc,id desc')->limit(2)->select();
        // 推荐其他户型
        $data['recommend_layout_data'] = $model->with(['house'])->where('house_id', 'neq', $info['house_id'])->where('house.status', 'normal')->where('house_layout.status', 'normal')->where('house.city', 'eq', $info['house']['city'])->where('house.region', 'eq', $info['house']['region'])->where('house_layout.room_num', $info['room_num'])->orderRaw('weigh desc,id desc')->limit(3)->select();
        $layoutQrcodeModel = new \app\common\model\xiluhouse\HouseLayoutQrcode;
        $exist = $layoutQrcodeModel->where('house_layout_id', $id)->where('user_id', $this->auth->id)->find();
        if ($exist) {
            $data['share_qrcode_text'] = cdnurl($exist['url'],true);
        } else {
            $wxmini = new \app\common\library\xiluhouse\Wxmini;
            $res = $wxmini->getWXacode('user_' . $this->auth->id . ',houselayout_' . $id, 'pages/house/huxing_detail/huxing_detail');
            if(!$res) $this->error('获取小程序二维码失败');
            $root = '.';
            $filename = md5(mt_rand()).'.png';
            $path = "/uploads/".date('Ymd').'/';
            if (!file_exists($root . $path)) {
                @mkdir($root . $path, 0777, true);
            }
            $qrcode = $path.$filename;
            if(!get_addon_config('alioss')){
                file_put_contents($root.$qrcode,$res);
            }else{
                Common::uploadAlioss($path, $res);
            }
            if ($qrcode) {
                $layoutQrcodeModel->insert(['house_layout_id' => $id, 'user_id' => $this->auth->id, 'url' => $qrcode]);
            }
            if(!$qrcode){
                $qrcode = \app\common\model\xiluhouse\Config::getdatas('wxmini_logo');
            }
            $data['share_qrcode_text'] = cdnurl($qrcode,true);
        }

        $this->success('', $data);
    }

    /**
     * @title   领取免费专车统计数量
     * @desc    领取免费专车统计数量
     */
    public function free_car_num()
    {
        $model = new \app\common\model\xiluhouse\AppointLog;
        $num = $model->where('type', 3)->count() ?: 0;
        $this->success('', $num);
    }

    /**
     * @title   领取免费专车、免费咨询、订阅变价通知、开盘通知、实时动态、帮你找房、领取优惠券
     * @desc    领取免费专车、免费咨询、订阅变价通知、开盘通知、实时动态、帮你找房、领取优惠券
     * @param int $type                         1    分类:1=订阅动态,2=留电咨询,3=领取免费专车,4=帮你找房,5=咨询房价走势,6=领取优惠券
     * @param int $subscribe_type               0    订阅通知类型:0=无订阅,1=订阅变价通知,2=订阅开盘通知,3=订阅实时动态
     * @param int $house_id                     0    房源id
     * @param int $broker_user_id               0    关联经纪人id
     * @param string $mobile                    无   手机号
     * @param int $gender                       0    性别:0=未知,1=男,2=女
     * @param date $view_date                   无   看房时间
     * @param int $min_total_price              0    最低购房预算(万元)
     * @param int $max_total_price              0    最高购房预算(万元)
     * @param string $prov                      无   省
     * @param string $city                      无   省
     * @param string $region                    无   省
     * @param string $house_search_roomnum_ids  无   户型ids
     *  @param string $orther_areas             无   区县街道
     *  @param string $remark             无          用户备注
     */
    public function create_appoint_log()
    {
        $param['type'] = $this->request->param('type/d', 0);
        $param['subscribe_type'] = $this->request->param('subscribe_type/d', 0);
        $param['house_id'] = $this->request->param('house_id/d', 0);
        $param['broker_user_id'] = $this->request->param('broker_user_id/d', 0);
        $param['mobile'] = $this->request->param('mobile/s', '');
        $param['gender'] = $this->request->param('gender/d', 0);
        $param['view_date'] = $this->request->param('view_date/s', NULL);
        $param['min_total_price'] = $this->request->param('min_total_price/f', 0);
        $param['max_total_price'] = $this->request->param('max_total_price/f', 0);
        $param['prov'] = $this->request->param('prov/s', '');
        $param['city'] = $this->request->param('city/s', '');
        $param['region'] = $this->request->param('region/s', '');
        $param['orther_areas'] = $this->request->param('orther_areas/s', '');
        $param['remark'] = $this->request->param('remark/s', '');
        $param['house_search_roomnum_ids'] = $this->request->param('house_search_roomnum_ids/s', '');
        $param['user_id'] = $this->auth->id;
        if ($param['broker_user_id'] == $param['user_id']) {
            $this->error('无法预约自己哦');
        }
        $model = new \app\common\model\xiluhouse\AppointLog;
        Db::startTrans();
        try {
            $result = $model->createNowLog($param);
            if (!$result) {
                exception('提交失败');
            }
            $task_log_model = new \app\common\model\xiluhouse\TaskLog;
            $task_log_model->addtasklog(2, $this->auth->id);
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('提交成功');
    }

    /**
     * @title   返现券领取记录
     * @desc    返现券领取记录
     * @param int $house_id                     0    楼盘id
     * @param string $page_type                    0    页面类型:wlsf=五牛送福房,hhmz=环沪明珠,hqsq=虹桥商圈,hzy=汇总页,detail=楼盘详情页
     * @param string $mobile                    无   手机号
     * @param string $ip                           0    IP
     * @param string $device_number                无   设备号
     * @param string $device_type                   无   设备类型:ios=苹果,android=安卓,orther=其他
     * @param string $device_name                   无   设备名称
     */
    public function create_special_log()
    {
        $param['page_type'] = $this->request->param('page_type/s', '');
        $param['house_id'] = $this->request->param('house_id/d', 0);
        $param['mobile'] = $this->request->param('mobile/s', '');
        $param['ip'] = $this->request->param('ip/s', '');
        $param['ip'] = $param['ip'] ? $param['ip'] : request()->ip();
        $param['device_number'] = $this->request->param('device_number/s', '');
        $param['device_type'] = $this->request->param('device_type/s', '');
        $param['device_name'] = $this->request->param('device_name/s', '');
        $param['user_id'] = $this->auth ? $this->auth->id : 0;
        $model = new \app\common\model\xiluhouse\SpecialLog;
        $exist = $model->where('mobile', $param['mobile'])->find();

        if ($exist) {
            $this->success('您已领取过返现券', null, 101);
        }
        if ($this->platform == 'ios' || $this->platform == 'android' || $param['device_number']) {
            $exist2 = $model->where('device_number', $param['device_number'])->find();
            if ($exist2) {
                $this->success('您已领取过返现券', null, 101);
            }
        }
        $result = $model->save($param);
        if (!$result) {
            $this->error('提交失败');
        }
        $this->success('提交成功');
    }

    /**
     * @title   评价房源、评价经纪人
     * @desc    评价房源、评价经纪人
     * @param int $house_id             0   房源id
     * @param int $type                 1   类型:1=楼盘评价,2=经纪人评价
     * @param int $comment_type         1   点评房源人类型:1=用户点评,2=经纪人点评
     * @param int $broker_user_id       0   关联经纪人
     * @param int $identity_type        1   评价人身份:1=考虑看房,2=看过该房,3=我是业主,4=我是游客
     * @param int $view_date            无  看房时间
     * @param int $star                 5   评分
     * @param string $content              无  评价内容
     * @param string $images              无   评价图片
     */
    public function comment()
    {
        $params['house_id'] = $this->request->param('house_id/d', 0);
        $params['type'] = $this->request->param('type/d', 1);
        $params['comment_type'] = $this->request->param('comment_type/d', 1);
        $params['broker_user_id'] = $this->request->param('broker_user_id/d', 0);
        if ($params['type'] == 1) {
            $userInfo = \app\common\model\xiluhouse\UserProfile::where('user_id', $this->auth->id)->find();
            if ($userInfo['is_broker'] == 2) {
                $params['comment_type'] = 2;
                $params['broker_user_id'] = $this->auth->id;
            } else {
                $params['comment_type'] = 1;
            }
        }

        $params['identity_type'] = $this->request->param('identity_type/d', 1);
        $params['view_date'] = $this->request->param('view_date/s', NULL);
        $params['star'] = $this->request->param('star/d', 5);
        $params['content'] = $this->request->param('content/s', '');
        $params['images'] = $this->request->param('images/s', '');
        if (($params['type'] == 1 && !$params['house_id']) || ($params['type'] == 2 && !$params['broker_user_id']) || !$params['content']) {
            $this->error('参数错误');
        }
        // 验证敏感词
        $wxmini = new \app\common\library\xiluhouse\Wxmini();
        $check_result = $wxmini->checkContent($params['content']);
        if ($check_result['errcode'] != 0) {
            $this->error($check_result['errmsg']);
        }
        $params['user_id'] = $this->auth->id;
        $model = new \app\common\model\xiluhouse\Comment;
        $res = $model->editData($params);
        if (!$res) {
            $this->error('提交失败');
        }
        $this->success('提交成功');
    }

    /**
     * @title   评论统计数据
     * @desc    评论统计数据
     * @param int $house_id             0   房源id
     * @param int $type                 1   类型:1=楼盘评价,2=经纪人评价
     * @param int $broker_user_id       0   关联经纪人
     */
    public function comment_info()
    {
        $map = [];
        $house_id = $this->request->param('house_id/d', 0);
        if ($house_id) {
            $map['house_id'] = $house_id;
        }
        $type = $this->request->param('type/d', 1);
        if ($type) {
            $map['type'] = $type;
        }
        $broker_user_id = $this->request->param('broker_user_id/d', 0);
        if ($broker_user_id) {
            $map['broker_user_id'] = $broker_user_id;
        }

        $model = new \app\common\model\xiluhouse\Comment;
        $data['user_comment_all_count'] = $model->where($map)->where('comment_type', 1)->count();
        $data['user_comment_good_count'] = $model->where($map)->where('comment_type', 1)->where('star', 5)->count();
        $data['user_comment_medium_count'] = $model->where($map)->where('comment_type', 1)->where('star', 'in', '3,4')->count();
        $data['user_comment_image_count'] = $model->where($map)->where('comment_type', 1)->where('images', 'not null')->where('images', 'neq', '')->count();
        $data['broker_comment_all_count'] = $model->where($map)->where('comment_type', 2)->count();
        $data['broker_comment_good_count'] = $model->where($map)->where('comment_type', 2)->where('star', 5)->count();
        $data['broker_comment_medium_count'] = $model->where($map)->where('comment_type', 2)->where('star', 'in', '3,4')->count();
        $data['broker_comment_image_count'] = $model->where($map)->where('comment_type', 2)->where('images', 'not null')->where('images', 'neq', '')->count();
        $this->success('', $data);
    }

    /**
     * @title   用户点评列表、咨询师点评列表
     * @desc    用户点评列表、咨询师点评列表
     * @param int $house_id             0   房源id
     * @param int $type                 1   类型:1=楼盘评价,2=经纪人评价
     * @param int $comment_type         1   点评房源人类型:1=用户点评,2=经纪人点评
     * @param int $broker_user_id       0   关联经纪人
     * @param int $search_type          1   搜索类型：1=全部，2=好评，3=中评，4=有图，5=最新
     */
    public function comment_list()
    {
        $model = new \app\common\model\xiluhouse\Comment;

        $house_id = $this->request->param('house_id/d', 0);
        if ($house_id) {
            $map['comment.house_id'] = $house_id;
        }
        $type = $this->request->param('type/d', 1);
        if ($type) {
            $map['comment.type'] = $type;
        }
        $comment_type = $this->request->param('comment_type/d', 1);
        if ($comment_type) {
            $map['comment.comment_type'] = $comment_type;
        }
        $broker_user_id = $this->request->param('broker_user_id/d', 0);
        if ($broker_user_id) {
            $map['comment.broker_user_id'] = $broker_user_id;
        }
        $search_type = $this->request->param('search_type/d', 1);
        switch ($search_type) {
            case 2:
                # 好评
                $map['star'] = 5;
                break;
            case 3:
                # 中评
                $map['star'] = ['in', '3,4'];
                break;
            case 4:
                # 有图
                $map['comment.images'] = 'not null';
                $map['comment.images'] = ['neq', ''];
                break;
                // case 5:
                //     # 最新
                //     break;
            default:
                # code...
                break;
        }

        $list = $model->with(['user'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'house'])->where($map)->orderRaw('id desc')->paginate();
        foreach ($list as $key => $value) {
            $value->append(['is_like']);
        }
        $this->success('', $list);
    }

    /**
     * @title   楼盘评价、经纪人评价
     * @desc    楼盘评价、经纪人评价
     * @param int $type                 1   类型:1=楼盘评价,2=经纪人评价
     * @param int $search_type          1   搜索类型：1=全部，2=好评，3=中评，4=有图，5=最新
     */
    public function my_comment_list()
    {
        $model = new \app\common\model\xiluhouse\Comment;
        $map['comment.user_id'] = $this->auth->id;
        $type = $this->request->param('type/d', 1);
        if ($type) {
            $map['comment.type'] = $type;
        }
        $search_type = $this->request->param('search_type/d', 1);
        switch ($search_type) {
            case 2:
                # 好评
                $map['star'] = 5;
                break;
            case 3:
                # 中评
                $map['star'] = ['in', '3,4'];
                break;
            case 4:
                # 有图
                $map['comment.images'] = 'not null';
                $map['comment.images'] = ['neq', ''];
                break;
                // case 5:
                //     # 最新
                //     break;
            default:
                # code...
                break;
        }

        $list = $model->with(['broker'=>function($query){
            $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
        }, 'house'])->where($map)->orderRaw('id desc')->paginate();
        foreach ($list as $key => $value) {
            $value->append(['is_like']);
        }
        $this->success('', $list);
    }

    /**
     * @title   对评论进行点赞
     * @desc    对评论进行点赞
     * @param int $id             0   评论id
     */
    public function like_comment()
    {
        $id = $this->request->param('id/d', 0);
        if (!$id) {
            $this->error('参数错误：评论id必传');
        }
        $model = new \app\common\model\xiluhouse\Comment;
        $info = $model->get($id);
        if (!$info) {
            $this->error('不存在该评论');
        }

        $like_model = new \app\common\model\xiluhouse\CommentLike;
        $exist = $like_model->where('comment_id', $id)->where('user_id', $this->auth->id)->find();
        if ($exist) {
            $this->success('点赞成功');
        }
        // 启动事务
        Db::startTrans();
        try {
            $res = $like_model->save([
                'comment_id' => $id,
                'user_id' => $this->auth->id,
            ]);
            if (!$res) {
                exception('提交失败，请稍后提交');
            }
            $res = $info->setInc('like_num');
            if (!$res) {
                exception('提交失败，请稍后提交');
            }
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('点赞成功');
    }
    /**
     * @title 客户公海订单列表
     * @desc  
     *
     */
    public function my_appoint_log_list()
    {
        $model = new \app\common\model\xiluhouse\AppointLog;
        $list = $model
            ->with(['broker'=>function($query){
                $query->withField(['id','avatar','nickname','username','bio','score','mobile']);
            }, 'house'])
            ->where('rental_id', 0)
            ->where('user_id', $this->auth->id)
            ->orderRaw('id desc')
            ->paginate();

        $this->success('', $list);
    }
}
